package org.yzhang3.data.utils;

import java.util.List;

import org.yzhang3.data.common.Constants;

public class IntegerUtils {
	
	/**
	 * convert one int value to one byte.
	 * @param b
	 * @return
	 */
	public static byte toByte(int b) {
		return (byte) (b > 127 ? 127 - b : b);
//		return (byte) b;
	}
	
	/**
	 * convert one int array to one byte array
	 * @param ints
	 * @param bs
	 */
	public static byte[] toByte(int[] ints) {
		byte[] bs = new byte[ints.length];
		for (int i=0; i<ints.length; i++) {
			bs[i] = toByte(ints[i]);
		}
		return bs;
	}
	
	/**
	 * Get <code>b</code>'s last 8 bits.
	 * @param b
	 * @return
	 */
	public static String to8Bits(int b) {
		return StringUtils.format(Integer.toBinaryString(b & Constants.BYTE_MASK[Constants.BITS_PRE_BYTE]), Constants.BITS_PRE_BYTE);
	}
	
	/**
	 * sum <code>ints</code> together.
	 * @param ints
	 * @return
	 */
	public static int sum(int... ints) {
		int result = 0;
		for (int i=0; i<ints.length; i++) {
			result = result + ints[i];
		}
		return result;
	}
	
	/**
	 * Convert the <code>target</code> to one integer, and target is binary.<br>
	 * <b>NOTE: </b> <code>target</code>'s length must be less than 32.
	 * @param binary
	 * @return
	 */
	public static int toInt(String binary) {
		byte[] bs = binary.getBytes();
		int result = 0;
		int len = bs.length;
		for (int i = 0; i < len; i++) {
			result = result + ((int) bs[i] - 48) * Constants.BINARY_POWS[len - 1 - i];
		}

		if (0 > result) {
			result = result + 1;
		}

		return result;
	}
	
	public static byte[] toByteArray(List<Integer> datas) {
		byte[] ds = new byte[datas.size()];
		for (int i=0; i<ds.length; i++) {
			ds[i] = toByte(datas.get(i).intValue());
		}
		return ds;
	}
	
	
	
	public static void main(String[] args) {
		String binary = "1010001";
		System.out.println(toInt(binary));
		
		int ii = 255;
		System.out.println(toByte(ii));
		System.out.println(toByte(ii-1));
		System.out.println(toByte(ii-2));
	}
	
}
